package com.kongmou.springSecurity.config;

import com.kongmou.springSecurity.security.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{//扩展

    @Bean
    UserDetailsService customUserService(){//2注册
        return new CustomUserService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //自定义认证
        auth.userDetailsService(customUserService()).passwordEncoder(passwordEncoder());
    }

    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated() //4所用请求需要认证即登录后才能访问
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .permitAll() //5定义登录行为，登录页面可任意访问
                .and()
                .logout().permitAll(); //6定义注销行为，注销请求可任意访问
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return  charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                if(charSequence.toString().equals(s)){
                    return true;
                }
                return false;
            }
        };
        return encoder;
    }

    // 忽略静态资源的拦截
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/static/**");
    }
}
